// const WebSocket = require('ws');

// var ws = new WebSocket('ws://localhost:8080');

// // 当 WebSocket 连接建立成功时，会触发 open 事件，并执行回调函数
// ws.onopen = function() {
//     console.log('WebSocket connection established');
//     ws.send('Hello from client!');
// };

// // 当客户端接收到来自服务器的消息时，会触发 message 事件
// ws.onmessage = function(event) {
//     console.log(`Received message: ${event.data}`);
// };

// // 当 WebSocket 连接关闭时，会触发 close 事件，
// ws.onclose = function(event) {
//     console.log('WebSocket connection closed');
// };

// // 当 WebSocket 连接发生错误时，会触发 error 事件，并执行回调函数
// ws.onerror = function(error) {
//     console.error('WebSocket error:', error);
// };


// const { MongoClient } = require('mongodb');
// const uri = 'mongodb://localhost:27017'; // 请替换为你的MongoDB连接字符串
// const client = new MongoClient(uri);

// async function connect() {
//   try {
//     await client.connect();
//     console.log('Connected to the database');
//   } catch (error) {
//     console.error('Failed to connect to the database:', error);
//   }
// }

// connect();
const express = require('express'); 
const WebSocket = require('ws');
const http = require('http');

const app = express()
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
const mongoose = require("mongoose")

// 链接数据库并创建好数据库的hahahadang会被自动创建
mongoose.connect("mongodb://127.0.0.1:27017/hahahadang_project")  

const Schema = mongoose.Schema
const UserType = {
    username: String,
    address: String,
    tel: String
}

const UserModel = mongoose.model("user", new Schema(UserType))

wss.on('connection', function connection(ws) {
    ws.on('message', function incoming(message) {
        console.log('Received data from server: %s', message);
        const data = JSON.parse(message);
        console.log(data);
        // Process the data as needed, e.g., store in a database
        const { eventMessage, username, address, tel } = data
       
        // 获取数据
        if (eventMessage == 0) { 
            UserModel.find({}, ["username", "address","tel", "_id"]).then(res => {
                // console.log(res);   
                ws.send(JSON.stringify(res))
            })
        }
        else if (eventMessage == 1) {
            UserModel.create({ username, address, tel }).then(res => {
                console.log('添加成功');
                // ws.send('添加成功')
            })
        }
        // 修改
        else if (eventMessage == 2) {
            const { id } = data
            UserModel.updateOne({
                _id:id
            }, { username, address, tel }).then(res => {
                console.log('修改成功');
                
            }) 
        }
            // 删除
        else if (eventMessage == 3) {
            const { id } = data
            UserModel.deleteOne({
                _id:id
            }).then(res => {
                console.log('删除成功');
                
            })
            }
    });

    // ws.send('我是控制数据库的后台');
});

server.listen(8081, () => {
    console.log('DataBase server is running on http://localhost:8081');
});